package org.hilo.boot.core.logback;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * 敏感信息脱敏处理
 * 
 * @author zollty
 * @since 2018-04-19
 */
public class SensitiveDataConverter extends MessageConverter {

    static Map<Integer, Pattern> patterns = new LinkedHashMap<Integer, Pattern>();
    static {
        // 手机号
        // ((86)?1[356789][0-9]{9})
        patterns.put(0, Pattern.compile("\\b((86)?(13[0-9]|15[0-3,5-9]|18[0-9]|19[89]|17[0135678]|166|14[579])\\d{8})\\b"));
        // 身份证 - "\\b([0-9]{17}X|[0-9]{18})\\b"
        patterns.put(1, Pattern.compile("\\b([1-9]\\d{5}[12][0-9]{3}[01][0-9][0-3][0-9]\\d{3}[0-9X])\\b"));
        // 银行卡
        patterns.put(2, Pattern.compile("\\b([45][0-9]{11,15}|62[0-9]{14,17})\\b"));
    }

    @Override
    public String convert(ILoggingEvent event) {
        // 获取原始日志
        String oriLogMsg = event.getFormattedMessage();

        // 获取脱敏后的日志
        for (Map.Entry<Integer, Pattern> entry : patterns.entrySet()) {
            oriLogMsg = SensitiveInfoUtils.matchAndReplace(oriLogMsg, 
                    entry.getValue(), entry.getKey());
        }

        return oriLogMsg;
    }

}
